<template>
  <div class="p-4 space-y-6 flex flex-col items-center min-h-screen bg-gray-50">
    <h2 class="text-2xl font-bold mb-4 text-blue-400">📑账单列表</h2>

    <!-- 筛选 -->
    <div class="flex flex-wrap gap-4 mb-4">
      <select v-model="selectedType" class="border p-2 rounded">
        <option value="">全部类型</option>
        <option value="支出">支出</option>
        <option value="收入">收入</option>
      </select>
      <select v-model="selectedCategory" class="border p-2 rounded">
        <option value="">所有分类</option>
        <option v-for="c in filterCategories" :key="c.id" :value="c.name">{{ c.name }}</option>
      </select>
      <select v-model="selectedMonth" class="border p-2 rounded">
        <option value="">所有时间</option>
        <option v-for="month in uniqueMonths" :key="month" :value="month">{{ month }}</option>
        <option value="custom">自定义时间段</option>
      </select>
      <div v-if="selectedMonth === 'custom'" class="flex gap-2 items-center">
        <input v-model="customStart" type="date" class="border p-2 rounded" />
        <span>至</span>
        <input v-model="customEnd" type="date" class="border p-2 rounded" />
      </div>
    </div>

    <!-- 表格 -->
    <div class="w-full flex justify-center">
      <table class="min-w-fit bg-white rounded shadow overflow-hidden text-center">
        <thead class="bg-gray-100 text-gray-700">
          <tr>
            <th class="px-4 py-2 text-center">时间</th>
            <th class="px-4 py-2 text-center">类型</th>
            <th class="px-4 py-2 text-center">分类</th>
            <th class="px-4 py-2 text-center">金额</th>
            <th class="px-4 py-2 text-center">备注</th>
            <th class="px-4 py-2 text-center">操作</th>
          </tr>
        </thead>
        <tbody>
          <tr v-for="bill in paginatedBills" :key="bill.id">
            <td class="px-4 py-2 text-center">
              {{ formatDateTime(bill.date) }}
            </td>
            <td class="px-4 py-2 text-center">
              <span :class="bill.categoryType === '收入' ? 'text-green-500' : 'text-red-500'">
                {{ bill.categoryType }}
              </span>
            </td>
            <td class="px-4 py-2 text-center">{{ bill.category }}</td>
            <td class="px-4 py-2 text-center">{{ bill.amount }}</td>
            <td class="px-4 py-2 text-center">{{ bill.note }}</td>
            <td class="px-4 py-2 flex flex-row gap-2 justify-center items-center">
              <button class="px-2 py-1 bg-yellow-300 hover:bg-yellow-400 text-xs rounded"
                @click="openEdit(bill)">编辑</button>
              <button class="px-2 py-1 bg-red-400 hover:bg-red-500 text-xs text-white rounded"
                @click="openDeleteDialog(bill)">删除</button>
            </td>
          </tr>
          <tr v-if="filteredBills.length === 0">
            <td class="px-4 py-2 text-center text-gray-400" colspan="6">暂无数据</td>
          </tr>
        </tbody>
      </table>
    </div>

    <!-- 分页控件 -->
    <div class="mt-4 flex justify-center items-center gap-2" v-if="pageCount > 1">
      <button class="px-3 py-1 rounded bg-gray-200" :disabled="currentPage === 1" @click="currentPage--">上一页</button>
      <span class="text-base text-gray-700">第 {{ currentPage }} / {{ pageCount }} 页</span>
      <button class="px-3 py-1 rounded bg-gray-200" :disabled="currentPage === pageCount"
        @click="currentPage++">下一页</button>
    </div>

    <!-- 编辑弹窗 -->
    <transition name="fade">
      <div v-if="showEdit" class="fixed inset-0 bg-black bg-opacity-40 flex items-center justify-center z-50"
        @click.self="closeEdit">
        <transition name="pop">
          <div class="bg-white p-6 rounded-lg shadow-xl w-full max-w-sm" v-if="showEdit">
            <h3 class="text-lg font-semibold mb-4">编辑账单</h3>
            <div class="space-y-3">
              <div>
                <label class="block text-sm mb-1">时间</label>
                <!-- step="1" 精确到秒 -->
                <input v-model="editForm.date" type="datetime-local" step="1" class="border w-full p-2 rounded" />
              </div>
              <div>
                <label class="block text-sm mb-1">类型</label>
                <select v-model="editForm.categoryType" class="border w-full p-2 rounded" @change="onEditTypeChange">
                  <option value="支出">支出</option>
                  <option value="收入">收入</option>
                </select>
              </div>
              <div>
                <label class="block text-sm mb-1">分类</label>
                <select v-model="editForm.category" class="border w-full p-2 rounded">
                  <option v-for="c in editCategories" :key="c.id" :value="c.name">{{ c.name }}</option>
                </select>
              </div>
              <div>
                <label class="block text-sm mb-1">金额</label>
                <input v-model="editForm.amount" type="number" step="0.01" class="border w-full p-2 rounded" />
              </div>
              <div>
                <label class="block text-sm mb-1">备注</label>
                <input v-model="editForm.note" class="border w-full p-2 rounded" />
              </div>
            </div>
            <div class="flex gap-2 mt-6 justify-end">
              <button class="bg-gray-300 px-4 py-1 rounded" @click="closeEdit">取消</button>
              <button class="bg-blue-400 px-4 py-1 text-white rounded" @click="submitEdit">保存</button>
            </div>
          </div>
        </transition>
      </div>
    </transition>
    <!-- 删除弹窗 -->
    <transition name="fade">
      <div v-if="showDeleteDialog" class="fixed inset-0 bg-black bg-opacity-40 flex items-center justify-center z-50"
        @click.self="closeDeleteDialog">
        <transition name="pop">
          <div class="bg-white p-6 rounded-lg shadow-xl w-full max-w-sm" v-if="showDeleteDialog">
            <h3 class="text-lg font-semibold mb-4 text-red-500">确认删除账单？</h3>
            <div class="space-y-3 text-gray-600">
              <div><b>时间：</b>{{ formatDateTime(deleteBillInfo.date) }}</div>
              <div><b>类型：</b>{{ deleteBillInfo.categoryType }}</div>
              <div><b>分类：</b>{{ deleteBillInfo.category }}</div>
              <div><b>金额：</b>{{ deleteBillInfo.amount }}</div>
              <div><b>备注：</b>{{ deleteBillInfo.note }}</div>
            </div>
            <div class="flex gap-2 mt-6 justify-end">
              <button class="bg-gray-300 px-4 py-1 rounded" @click="closeDeleteDialog">取消</button>
              <button class="bg-red-500 px-4 py-1 text-white rounded" @click="confirmDeleteBill">确认删除</button>
            </div>
          </div>
        </transition>
      </div>
    </transition>

  </div>
</template>

<script setup>
import { ref, computed, onMounted, watch } from 'vue'
import axios from 'axios'

// 工具函数
// datetime-local ("2025-05-29T14:36:56") -> "2025-05-29 14:36:56"
function toDateTimeString(dt) {
  if (!dt) return ''
  const [date, time] = dt.split('T')
  if (!date || !time) return ''
  return `${date} ${time.length === 5 ? time + ':00' : time}` // 没有秒补:00
}
// "2025-05-29 14:36:56" -> "2025-05-29T14:36:56"
function toDateTimeLocalString(dt) {
  if (!dt) return ''
  return dt.replace(' ', 'T')
}
// 只做简单显示格式化
function formatDateTime(dt) {
  // 只要传入数据本身有秒，直接展示
  if (!dt) return ''
  return dt.replace('T', ' ')
}

const userId = localStorage.getItem('user_id')
const bills = ref([])

const selectedType = ref('')
const selectedCategory = ref('')
const selectedMonth = ref('')
const customStart = ref('')
const customEnd = ref('')

// 分类数据
const allCategories = ref([])
const filterCategories = ref([])
const editCategories = ref([])

const pageSize = 14
const currentPage = ref(1)
const paginatedBills = computed(() => {
  const start = (currentPage.value - 1) * pageSize
  return filteredBills.value.slice(start, start + pageSize)
})
const pageCount = computed(() => Math.ceil(filteredBills.value.length / pageSize))

const filteredBills = computed(() => {
  let list = bills.value
  if (selectedType.value) list = list.filter(b => b.categoryType === selectedType.value)
  if (selectedCategory.value) list = list.filter(b => b.category === selectedCategory.value)
  if (selectedMonth.value && selectedMonth.value !== 'custom') {
    list = list.filter(b => b.date.startsWith(selectedMonth.value))
  }
  if (selectedMonth.value === 'custom' && customStart.value && customEnd.value) {
    list = list.filter(b => b.date.slice(0, 10) >= customStart.value && b.date.slice(0, 10) <= customEnd.value)
  }
  return list
})

const uniqueMonths = computed(() => {
  const set = new Set()
  bills.value.forEach(b => {
    if (b.date && b.date.length >= 7) set.add(b.date.slice(0, 7))
  })
  return Array.from(set)
})

const fetchBills = async () => {
  try {
    const res = await axios.post('http://localhost:3000/api/get-bills', { user_id: userId })
    bills.value = res.data.bills || []
    currentPage.value = 1
  } catch (e) {
    console.error(e)
  }
}

const fetchCategories = async (type = '') => {
  try {
    const res1 = await axios.post('http://localhost:3000/api/get-categories', { user_id: userId, type: '支出' })
    const res2 = await axios.post('http://localhost:3000/api/get-categories', { user_id: userId, type: '收入' })
    allCategories.value = [...(res1.data.categories || []), ...(res2.data.categories || [])]
    if (type) {
      filterCategories.value = allCategories.value.filter(c => c.type === type)
    } else if (selectedType.value) {
      filterCategories.value = allCategories.value.filter(c => c.type === selectedType.value)
    } else {
      filterCategories.value = allCategories.value
    }
  } catch (e) {
    console.error(e)
  }
}
watch(selectedType, () => {
  fetchCategories()
  selectedCategory.value = ''
})
onMounted(() => {
  fetchCategories()
})

const applyCustomDate = () => {
  selectedMonth.value = ''
}

// 编辑弹窗
const showEdit = ref(false)
const editForm = ref({
  id: '',
  amount: '',
  category: '',
  categoryType: '',
  note: '',
  date: ''
})

const openEdit = async bill => {
  editForm.value = {
    ...bill,
    date: toDateTimeLocalString(bill.date)
  }
  await updateEditCategories(bill.categoryType)
  showEdit.value = true
}
const onEditTypeChange = async () => {
  await updateEditCategories(editForm.value.categoryType)
  editForm.value.category = editCategories.value.length ? editCategories.value[0].name : ''
}
const updateEditCategories = async type => {
  try {
    const res = await axios.post('http://localhost:3000/api/get-categories', { user_id: userId, type })
    editCategories.value = res.data.categories || []
    if (editCategories.value.length && !editCategories.value.some(c => c.name === editForm.value.category)) {
      editForm.value.category = editCategories.value[0].name
    }
  } catch (e) {
    editCategories.value = []
  }
}
const closeEdit = () => {
  showEdit.value = false
}
const submitEdit = async () => {
  try {
    const { id, amount, category, categoryType, note } = editForm.value
    let date = toDateTimeString(editForm.value.date)
    await axios.post('http://localhost:3000/api/update-bill', {
      id,
      user_id: userId,
      amount,
      category,
      categoryType,
      note,
      date
    })
    showEdit.value = false
    fetchBills()
  } catch (e) {
    alert('编辑失败')
    console.error(e)
  }
}
// 删除弹窗控制
const showDeleteDialog = ref(false)
const deleteBillInfo = ref({})

// 打开删除弹窗
const openDeleteDialog = bill => {
  deleteBillInfo.value = { ...bill }
  showDeleteDialog.value = true
}
const closeDeleteDialog = () => {
  showDeleteDialog.value = false
}

// 确认删除
const confirmDeleteBill = async () => {
  try {
    await axios.post('http://localhost:3000/api/delete-bill', {
      id: deleteBillInfo.value.id,
      user_id: userId
    })
    showDeleteDialog.value = false
    fetchBills()
  } catch (e) {
    alert('删除失败')
    console.error(e)
  }
}

// 监听筛选条件变化，回到第一页
watch([selectedType, selectedCategory, selectedMonth, customStart, customEnd], () => {
  currentPage.value = 1
})

onMounted(async () => {
  await fetchBills()
  await fetchCategories()
})
watch(currentPage, () => {
  window.scrollTo({ top: 0, behavior: 'smooth' })
})
</script>

<style scoped>
.min-w-fit {
  min-width: 750px;
}

.fade-enter-active,
.fade-leave-active {
  transition: opacity 0.3s cubic-bezier(.55, 0, .1, 1);
}

.fade-enter-from,
.fade-leave-to {
  opacity: 0;
}

.pop-enter-active,
.pop-leave-active {
  transition: all 0.2s cubic-bezier(.55, 0, .1, 1);
}

.pop-enter-from,
.pop-leave-to {
  transform: scale(0.9);
  opacity: 0;
}
</style>
